const Express = require("express");
const ResponseHelper = require("../ResponseHelper");
const router = Express.Router();
const ChineseMedicineService = require("../../servers/ChineseMedicineService");
const fileUrl = require("../../tools/fileUrl");
const fs = require("fs");
const path = require("path");
const XLSX = require("xlsx");

//分页获取
router.post("/getByPage", async (req, res) => {
  try {
    const { page, limit, where } = req.body.params;
    const result = await ChineseMedicineService.getByPage(page, limit, where);
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});

//添加记录
router.post("/add", async (req, res) => {
  try {
    const result = await ChineseMedicineService.create(req.body);
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});

//更新记录
router.post("/update/:id", async (req, res) => {
  const sn = req.params.id;
  const Obj = req.body;
  try {
    const result = await ChineseMedicineService.update(sn, Obj);
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
//根据sn删除记录
router.post("/del/:sn", async (req, res) => {
  try {
    const sn = req.params.id;
    const result = await ChineseMedicineService.delete(sn);
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
//批量删除记录
router.post("/bulkCreate", async (req, res) => {
  try {
    const data = req.body;
    const result = await ChineseMedicineService.bulkCreate(data);
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
router.get("/getDepartment", async (req, res) => {
  try {
    const result = await ChineseMedicineService.countByDepartment();
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
router.get("/getSex", async (req, res) => {
  try {
    const result = await ChineseMedicineService.countBySex();
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
router.get("/getAge", async (req, res) => {
  try {
    const result = await ChineseMedicineService.countByAge();
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
router.get("/getPos", async (req, res) => {
  try {
    const result = await ChineseMedicineService.countByPos();
    ResponseHelper.sendData(result, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});

router.post("/getPdfByName", async (req, res) => {
  try {
    const params = req.body.params;
    const name = params.name;
    const targetDir = path.join(fileUrl.PDFURL, name);
    const files = fs.readdirSync(targetDir);
    const pdfUrls = files
      .filter((file) => file.toLowerCase().endsWith(".pdf"))
      .map((file) => `http://localhost:5005/uploads/${name}/${file}`);
    ResponseHelper.sendData(pdfUrls, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
router.post("/getImgsByName", async (req, res) => {
  try {
    const params = req.body.params;
    const name = params.name;
    const targetDir = path.join(fileUrl.PDFURL, name);
    const files = fs.readdirSync(targetDir);
    const pdfUrls = files
      .filter((file) => file.toLowerCase().endsWith(".jpg"))
      .map((file) => `http://localhost:5005/uploads/${name}/${file}`);
    ResponseHelper.sendData(pdfUrls, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});
router.post("/getForceByName", async (req, res) => {
  try {
    const params = req.body.params;
    const name = params.name;
    const targetDir = path.join(fileUrl.PDFURL, name);
    const files = fs.readdirSync(targetDir);
    const excelFile = files.find((file) => file == "Data.csv");
    console.log("getForceByName excelFile", excelFile);
    if (!excelFile) {
      return ResponseHelper.sendData([], res);
    }
    const fullPath = path.join(targetDir, excelFile);
    // 读取 Excel 内容为 workbook
    const workbook = XLSX.readFile(fullPath);
    // 默认读取第一个 sheet
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    // 转换为 JSON，仅提取B列数据
    const jsonData = XLSX.utils
      .sheet_to_json(sheet, {
        header: 1,
      })
      .map((row) => row[1])
      .filter((cell) => cell !== undefined && cell !== null && cell !== "");
    // 返回 JSON 数据
    ResponseHelper.sendData(jsonData, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});

router.post("/getPoseByName", async (req, res) => {
  try {
    const params = req.body.params;
    const name = params.name;
    const targetDir = path.join(fileUrl.PDFURL, name);
    const files = fs.readdirSync(targetDir);
    const excelFile = files.find((file) => file == "Data.csv");
    console.log("getPoseByName excelFile", excelFile);
    if (!excelFile) {
      return ResponseHelper.sendData([], res);
    }
    const fullPath = path.join(targetDir, excelFile);
    // 读取 Excel 内容为 workbook
    const workbook = XLSX.readFile(fullPath);
    // 默认读取第一个 sheet
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    // 转换为 JSON
    const jsonData = XLSX.utils
      .sheet_to_json(sheet, {
        header: 1,
      })
      .map((row) => row[2])
      .filter((cell) => cell !== undefined && cell !== null && cell !== "");
    // 返回 JSON 数据
    ResponseHelper.sendData(jsonData, res);
  } catch (err) {
    ResponseHelper.sendErr(err, res);
  }
});

module.exports = router;
